//
//  SLPhotoBrowserController.m
//  SLPhotoBrowser
//
//  Created by S_LINE on 2020/6/21.
//  Copyright © 2020 S_LINE. All rights reserved.
//

#import "SLPhotoBrowserController.h"

#import <SLKit/SLKit.h>
#import "SLZoomImageView.h"
#import "UIImage+SLPBHelper.h"

@interface SLPhotoBrowserController () <UIScrollViewDelegate>

@property (nonatomic, assign) SLPhotoBrowserType browserType;

/// 返回按钮
@property (nonatomic, strong) UIButton *backButton;

/// scrollView
@property (nonatomic, strong) UIScrollView *scrollView;

/// 图片ImageView列表
@property (nonatomic, strong) NSMutableArray<UIImageView *> *imageViews;

/// 删除按钮
@property (nonatomic, strong) UIButton *deleteButton;

@end

@implementation SLPhotoBrowserController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupNavBar];
    [self setupView];
}

- (void)setupNavBar {
    self.navigationController.navigationBar.hidden = YES;
    self.navigationController.navigationBarHidden = YES;
}

- (void)setupView {
    for (UIView *view in self.view.subviews) {
        [view removeFromSuperview];
    }
    
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.scrollView = scrollView;
    [self.view addSubview:scrollView];
    scrollView.pagingEnabled = YES;
    scrollView.backgroundColor = [UIColor blackColor];
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.showsVerticalScrollIndicator = NO;
    scrollView.delegate = self;
    
    [self setupImageViews];
    
    [self setupDeleteButton];
}

- (void)setupImageViews {
    CGFloat scrollViewWidth = self.scrollView.bounds.size.width;
    CGFloat scrollViewHeight = self.scrollView.bounds.size.height;
    if (![SLSafe isEffectiveArray:self.images]) {
        return;
    }
    
    self.imageViews = [[NSMutableArray alloc] init];
    for (int i = 0; i < self.images.count; i++) {
        CGFloat imageViewX = self.imageViews.count * scrollViewWidth;
        CGFloat imageViewY = 0;
        CGFloat imageViewWidth = scrollViewWidth;
        CGFloat imageViewHeight = scrollViewHeight;
        CGRect imageViewFrame = CGRectMake(imageViewX, imageViewY, imageViewWidth, imageViewHeight);
        SLZoomImageView *imageView = [[SLZoomImageView alloc] initWithFrame:imageViewFrame];
        [self.scrollView addSubview:imageView];
        [self.imageViews sl_addObject:imageView];
        UITapGestureRecognizer *imageViewTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageViewTaped:)];
        [imageView addGestureRecognizer:imageViewTap];
        
        SLPhotoModel *photoModel = [self.images sl_objectAtIndex:i];
        if (photoModel.image) {
            imageView.image = photoModel.image;
        }
        else if ([SLSafe isEffectiveString:photoModel.imageUrl]) {
            imageView.imageUrl = [NSURL URLWithString:photoModel.imageUrl];
        }
    }
    self.scrollView.contentSize = CGSizeMake(scrollViewWidth * self.imageViews.count, 0);
    if (self.currentIndex > 0 &&
        self.currentIndex < self.imageViews.count) {
        self.scrollView.contentOffset = CGPointMake(self.currentIndex * scrollViewWidth, 0);
    }
}

- (void)setupDeleteButton {
    if (!self.isRemoveable) {
        return;
    }
    
    CGFloat deleteButtonWidth = 50.0;
    CGFloat deleteButtonY = CGRectGetHeight([UIScreen mainScreen].bounds) - 120;
    CGFloat deleteButtonX = (CGRectGetWidth([UIScreen mainScreen].bounds) - deleteButtonWidth) / 2.0;
    CGRect deleteButtonFrame = CGRectMake(deleteButtonX,
                                          deleteButtonY,
                                          deleteButtonWidth,
                                          deleteButtonWidth);
    self.deleteButton = [[UIButton alloc] initWithFrame:deleteButtonFrame];
    [self.view addSubview:self.deleteButton];
    self.deleteButton.alpha = 0.8;
    [self.deleteButton setImage:[UIImage slpb_imageNamed:@"slpb_delete"]
                  forState:UIControlStateNormal];
    [self.deleteButton addTarget:self
                          action:@selector(deleteButtonClickEvent:)
                forControlEvents:(UIControlEventTouchUpInside)];
}

- (instancetype)initWithBrowserType:(SLPhotoBrowserType)browserType {
    self = [super init];
    if (self) {
        self.browserType = browserType;
    }
    return self;
}

#pragma mark - 点击事件
/// 图片点击事件
- (void)imageViewTaped:(UITapGestureRecognizer *)sender {
    if (self.backActionBlock) {
        self.backActionBlock();
    }
}

/// 删除按钮点击事件
- (void)deleteButtonClickEvent:(UIButton *)sender {
    NSInteger index = self.scrollView.contentOffset.x / CGRectGetWidth(self.scrollView.bounds);
    if (index < 0 || index > self.imageViews.count) {
        return;
    }
    
    CGFloat scrollViewWidth = CGRectGetWidth(self.scrollView.bounds);
    UIImageView *imageView = self.imageViews[index];
    BOOL isLastImage = (index == (self.imageViews.count - 1));
    BOOL isFirstImage = (index == 0);
    [self.imageViews sl_removeObject:imageView];
    [self.images sl_removeObjectAtIndex:index];
    
    CGFloat imageViewX = CGRectGetMinX(imageView.frame);
    if (isLastImage && !isFirstImage) {
        imageViewX = CGRectGetMinX(imageView.frame) - scrollViewWidth;
    }
    CGRect imageViewFrame = CGRectMake(imageViewX,
                                       -CGRectGetHeight(imageView.frame),
                                       CGRectGetWidth(imageView.frame),
                                       CGRectGetHeight(imageView.frame));
    
    /// 图片移除动画
    [UIView animateWithDuration:0.3 animations:^{
        imageView.frame = imageViewFrame;
        imageView.alpha = 0;
    } completion:^(BOOL finished) {
        [imageView removeFromSuperview];
        if (self.photoRemovedCallBack) {
            self.photoRemovedCallBack(index);
        }
    }];
    
    if (self.imageViews.count == 0) {
        if (self.backActionBlock) {
            self.backActionBlock();
        }
        return;
    }
    
    if (isLastImage) {
        CGPoint newContentOffset = CGPointMake(self.scrollView.contentOffset.x - scrollViewWidth,
                                               self.scrollView.contentOffset.y);
        [UIView animateWithDuration:0.33 animations:^{
            self.scrollView.contentOffset = newContentOffset;
        }];
    }
    else {
        for (NSInteger i = index; i < self.imageViews.count; i++) {
            UIImageView *imageView = self.imageViews[i];
            CGRect newFrame = CGRectMake(CGRectGetMinX(imageView.frame) - scrollViewWidth,
                                         CGRectGetMinY(imageView.frame),
                                         CGRectGetWidth(imageView.bounds),
                                         CGRectGetHeight(imageView.bounds));
            [UIView animateWithDuration:0.33 animations:^{
                imageView.frame = newFrame;
            }];
        }
    }
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView != self.scrollView) {
        return;
    }
    
    for (SLZoomImageView *zoomImageView in self.imageViews) {
        if (zoomImageView.frame.origin.x != scrollView.contentOffset.x) {
            [zoomImageView recoverSize];
        }
    }
}

@end
